package wht.jly.forum.service.impl;

import com.querydsl.core.BooleanBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import wht.jly.forum.domain.QUser;
import wht.jly.forum.domain.User;
import wht.jly.forum.repository.UserRepository;
import wht.jly.forum.service.UserService;
import wht.jly.forum.utils.PropertyUtils;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

/**
 * @author lanyangji
 * @date 2019/2/9 17:50
 */
@Service
@Transactional(rollbackOn = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public Page<User> findByCondition(Integer page, Integer size, User user) {
        // 条件构造
        QUser dbUser = QUser.user;
        BooleanBuilder builder = new BooleanBuilder();
        if (!StringUtils.isEmpty(user.getUsername())) {
            builder.and(dbUser.username.like("%" + user.getUsername() + "%"));
        }
        if (!ObjectUtils.isEmpty(user.getBirthday())) {
            builder.and(dbUser.birthday.gt(user.getBirthday()));
        }
        if (user.getId() != null) {
            builder.or(dbUser.id.intValue().eq(user.getId()));
        }
        // 排序和分页
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, sort);

        return userRepository.findAll(builder, pageable);
    }

    @Override
    public User findByUsernameAndPassword(String username, String password) {
        return userRepository.findByUsernameAndPassword(username, password);
    }

    @Override
    public User findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    @Override
    public User updateById(User user) {
        if (user.getId() != null) {
            // 先查
            Optional<User> optional = userRepository.findById(user.getId());
            if (optional.isPresent()) {
                User dbUser = optional.get();
                // 非空复制
                BeanUtils.copyProperties(user, dbUser, PropertyUtils.getNullPropertyNames(user));
                // 修改
                return userRepository.save(dbUser);
            }
        }

        return null;
    }

    @Override
    public void deleteById(Integer id) {
        userRepository.deleteById(id);
    }

    @Override
    public List<String> findRoleCodeByUserId(Integer userId) {
        return userRepository.findRoleCodesByUserId(userId);
    }

    @Override
    public User save(User user) {
        return userRepository.save(user);
    }
}
